define([
	"UtilDir/util",
	"UtilDir/tool",
	"UtilDir/org/selectOrg",
	"UtilDir/searchBlock",
	"UtilDir/loading",
	"UtilDir/confirm",
	"http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
],function(Util, Tool, SelectOrg, SearchBlock, Loading, Confirm){

	var getQhRiskLevelMapController = function(){
		return getServer() + "/qh/qhRiskLevelMapProvince";
	};
	/**
	 * 页面初始化
	 */
	var init = function(){
		var t = setInterval(function () {
			if (T.MarkerClusterer) {
				clearInterval(t);
				initcreateProvince();
				initcreateProvince2();
				initcreateProvince3();
				downloadFile();
				uploadFile();
				queryBtnBind();
				initMap();
			}
		}, 10);
	};
	var initcreateProvince = function () {
		var html = '<option value="" selected>请选择</option>';
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" selected>请选择</option>';
			$("#citySelect option").remove();
			//$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append(html);
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			//if ($(this).val() == "") return;
			var html = '<option value="" selected>请选择</option>';
			$("#areaSelect option").remove();
			//$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	}
	var initcreateProvince2 = function () {
		var html = '<option value="" selected>请选择</option>';
		$("#citySelect2").append(html);
		$("#areaSelect2").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect2").append(html);
			}
		});
		$("#provinceSelect2").change(function () {
			var html = '<option value="" selected>请选择</option>';
			$("#citySelect2 option").remove();
			//$("#citySelect2").append(html);
			$("#areaSelect2 option").remove();
			$("#areaSelect2").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect2").append(html);
				$("#citySelect2").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect2").append(html);
				}
			});
		});
		$("#citySelect2").change(function () {
			//if ($(this).val() == "") return;
			var html = '<option value="" selected>请选择</option>';
			$("#areaSelect2 option").remove();
			//$("#areaSelect2").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect2").append(html);
				}
			});
		});
	}
	var initcreateProvince3 = function () {
		var html = '<option value="" selected>请选择</option>';
		$("#citySelect3").append(html);
		$("#areaSelect3").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect3").append(html);
			}
		});
		$("#provinceSelect3").change(function () {
			var html = '<option value="" selected>请选择</option>';
			$("#citySelect3 option").remove();
			//$("#citySelect3").append(html);
			$("#areaSelect3 option").remove();
			$("#areaSelect3").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect3").append(html);
				$("#citySelect3").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect3").append(html);
				}
			});
		});
		$("#citySelect3").change(function () {
			//if ($(this).val() == "") return;
			var html = '<option value="" selected>请选择</option>';
			$("#areaSelect3 option").remove();
			//$("#areaSelect3").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect3").append(html);
				}
			});
		});
	}

	var downloadFile = function () {
		$("#button-export").on("click", function () {
			var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
			window.location.href = getQhRiskLevelMapController() + "/download0?province=" + province + "&city=" + city + "&area=" + area;
			/*
			$.ajax({
				url: getQhProbabilityEarthquakeDangerController() + "/download0?province=" + province + "&city=" + city + "&area=" + area,
				contentType: "application/json",
				type: "get",
				success: function (data) {
					console.log(data);
					Util.alert(data);
				}
			});*/
		});
	}
	var uploadFile = function(){
		// 要上传的文件的后缀名数组
		var minList = [];
		// 要上传的文件的文件名数组
		var nameList = [];
		// var maxList = ["dbf","prj","shp","shx"];
		//上传文件类型选择
		$("#rlm-radio-shp").on("click",function(){//SHP文件
			var commentInfo = document.getElementById("commentInfo");
			commentInfo.setAttribute("placeholder", "导入多个文件时，文件名须相同");
			var selectfile = document.getElementById("button-selectfile");
			selectfile.setAttribute("accept",".shp,.dbf,.prj,.sbn,.sbx,.shp.xml,.shx");
		});
		$("#rlm-radio-gdb").on("click",function(){//GDB文件
			var commentInfo = document.getElementById("commentInfo");
			commentInfo.setAttribute("placeholder", "请上传gdb文件夹内的所有文件");
			var selectfile = document.getElementById("button-selectfile");
			selectfile.setAttribute("accept",".*");
		});
		// 获取文件名
		$("#button-selectfile").on("change", function () {
			//获取上传文件类型
			var rlmRadio = null;
			var obj = document.getElementsByName("rlm-radio")
			for (var i = 0; i < obj.length; i++) { //遍历Radio
				if (obj[i].checked) {
					rlmRadio = obj[i].value;
				}
			}
			if(rlmRadio=="shp"){
				var uploadinputFiles = document.getElementById("button-selectfile").files;
				minList = [];nameList = [];
				var text = "";
				for (var i = 0; i < uploadinputFiles.length; i++){
					console.log("uploading: " + uploadinputFiles[i].name);
					text += uploadinputFiles[i].name+"\n";
					// 获取这个文件的后缀名
					minList.push(uploadinputFiles[i].name.slice(uploadinputFiles[i].name.length-3,uploadinputFiles[i].name.length));
					nameList.push(uploadinputFiles[i].name.split(".")[0]);
				}
				$("#commentInfo").val(text);
			}else if(rlmRadio=="gdb"){
				var uploadinputFiles = document.getElementById("button-selectfile").files;
				minList = []; nameList = [];
				var text = "";
				for (var i = 0; i < uploadinputFiles.length; i++){
					console.log("uploading: " + uploadinputFiles[i].name);
					text += uploadinputFiles[i].name+"\n";
					// 获取这个文件的名称包括后缀名
					nameList.push(uploadinputFiles[i].name);
				}
				$("#commentInfo").val(text);
			}
		});

		$("#button-import").on("click", function () {
			var uploadinput = document.getElementById("button-selectfile");
			if (uploadinput.value == "") {
				Util.alert("上传前请先选择文件!");
				return;
			}
			//获取上传文件类型
			var rlmRadio = null;
			var obj = document.getElementsByName("rlm-radio")
			for (var i = 0; i < obj.length; i++) { //遍历Radio
				if (obj[i].checked) {
					rlmRadio = obj[i].value;
				}
			}
			if(rlmRadio=="shp"){
				if(!judgeIsOnce(minList)){
					//Util.alert('上传数量限制:.dbf、.prj、.shp、.shx文件各1个;.sbn、.sbx、.shp.xml文件至多一个。');
					Util.alert('上传数量限制:需.dbf、.shp、.shx文件各1个。');
					return;
				}else if(!judgeName(nameList)){
					Util.alert("文件名请保持一致！");
					return;
				}
			}else if(rlmRadio=="gdb"){
				if(!judgeIsOnceGdb(nameList)){
					Util.alert('需上传.gdb文件夹下的所有文件。');
					return;
				}
			}

			var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
			if(province == ""){
				Util.alert("请选择场地所在省份!");
				return;
			}
			/*if(city == ""){
				Util.alert("请选择场地所在市!");
				return;
			}
			if(area == ""){
				Util.alert("请选择场地所在区县!");
				return;
			}*/
			var formData = new FormData();
			for(var i = 0; i < uploadinput.files.length; i++){
				formData.append('files', uploadinput.files[i]);
			}
			formData.append("province", province);
			formData.append("city", city);
			formData.append("area", area);
			loading.show();
			$.ajax({
				url: getQhRiskLevelMapController() + "/upload",
				data: formData,
				processData: false, //因为data值是FormData对象，不需要对数据做处理。
				contentType: false,
				type: "POST",
				success: function (data) {
					if (data != null && data.GeometryIsNotEqualsCoordinate) {
						loading.close();
						/*var config = {
							message: '<span style="color: #FF0000;">提示：上传数据中属性信息的经度纬度小数点后六位未与空间信息的经纬值保持一致，请确认是否继续上传数据。<span>',
							events: {
								onConfirm: function(){
									confirmUploadLMPData(data.GeometryIsNotEqualsCoordinate, function (data) {
										uploadinput.value = null;
										$("#provinceSelect").val(""),
										$("#citySelect").val(""),
										$("#areaSelect").val(""),
										$("#commentInfo").val(""),
										Util.alert(data);
									});
								},
								onCancel: function(){
									//Util.alert("请将属性信息的经度纬度小数点后六位与空间信息的经纬值保持一致");
								},
								afterClose: function(){
								}
							}
						};
						Confirm(config);*/
						Util.alert('<span style="color: #FF0000;">提示：上传数据中属性信息的经度纬度小数点后六位未与空间信息的经纬值保持一致，请修改后再上传数据。<span>');
					} else {
						loading.close();
						uploadinput.value = null;
						$("#provinceSelect").val(""),
						$("#citySelect").val(""),
						$("#areaSelect").val(""),
						$("#commentInfo").val(""),
						Util.alert(data);
					}
				},
				error: function(xhr, state, errorThrown){
					loading.close();
					Util.alert("上传数据出现异常!");
				}
			});
		});
	}
	var confirmUploadLMPData = function (attrs, callback) {
		var tifFileName = attrs.affiliatedFileName, province = attrs.province, city = attrs.city, area = attrs.area;
		console.log(attrs);
		var formData = new FormData();
		formData.append("affiliatedFileName", tifFileName);
		formData.append("province", province);
		formData.append("city", city);
		formData.append("area", area);
		var url = getQhRiskLevelMapController() + "/postUpload"
		loading.show();
		$.ajax({
			url: url,
			data: formData,
			processData: false,
			contentType: false,
			type: "POST",
			success: function (data) {
				loading.close();
				callback(data);
				//Util.alert(data);
			},
			error: function(xhr, state, errorThrown){
				loading.close();
				Util.alert("上传数据出现异常!");
			}
		});
	};

	var queryBtnBind = function(){
		$("#operatePanelButton").click(function () {
			var operatePanel = $("#operatePanel");
			if (operatePanel.is(":visible")) {
				operatePanel.css("display", "none");
			} else {
				operatePanel.css("display", "block");
				$("#operatePanel2").css("display", "none");
				$("#operatePanel3").css("display", "none");
				$("#levelMapLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
				clearMarkers();
			}
			$('#qhRiskLevelMapInfo').hide(200); $("#qhRLMInfoClose").hide(200);
		});

		$("#levelMapLayers").click(function () {
			var sclImg = $("#levelMapLayersImg"), operatePanel2 = $("#operatePanel2");
			if (operatePanel2.is(":visible")) {
				sclImg.attr("src", "/qhwx/static/app/images/tucengoff.png");
				//clearMarkers();
				operatePanel2.css("display", "none");
			} else {
				sclImg.attr("src", "/qhwx/static/app/images/tucengon.png");
				operatePanel2.css("display", "block");
				$('#qhRiskLevelMapInfo').hide(200); $("#qhRLMInfoClose").hide(200);
				//getRiskLevelMapData();
				//createAffiliatedFileNameGridGrid();
				global_flag = "2";
			}
			$("#operatePanel").css("display", "none");
			$("#operatePanel3").css("display", "none");
			//$("#affiliatedFileNameGrid2").datagrid({data: []});
		});

		$("#levelMapLayersSearch").click(function () {
			var operatePanel3 = $("#operatePanel3");
			if (operatePanel3.is(":visible")) {
				operatePanel3.css("display", "none");
			} else {
				operatePanel3.css("display", "block");
				$('#qhRiskLevelMapInfo').hide(200); $("#qhRLMInfoClose").hide(200);
				global_flag = "3";
			}
			$("#operatePanel").css("display", "none");
			$("#operatePanel2").css("display", "none");
			$("#levelMapLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
			//$("#affiliatedFileNameGrid3").datagrid({data: []});
		});

		$("#operatePanel2CloseBtn").click(function () {
			$("#levelMapLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
			$("#operatePanel2").css("display", "none");
		});

		$("#operatePanel3CloseBtn").click(function () {
			$("#levelMapLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
			$("#operatePanel3").css("display", "none");
		});

		$("#closePanelBtn").click(function () {
			$("#operatePanel").css("display", "none");
		});

		$("#button-closeForm").click(function () {
			$("#operatePanel").css("display", "none");
		});

		$("#btnSearch").click(function () {
			createAffiliatedFileNameGridGrid("2");
			getRiskLevelMapData("2");
		});

		$("#btnSearch3").click(function () {
			createAffiliatedFileNameGridGrid("3");
			getRiskLevelMapData("3");
		});

		$("#qhRLMInfoClose").click(function () {
			$('#qhRiskLevelMapInfo').hide(200); $(this).hide();
		});
		$("#qhFieldInfoBtn").click(function () {
			showFieldInfo();
		});
		$("#qhFieldInfoClose").click(function () {
			$('#qhFieldInfo').hide(200);
		});


	};
	var judgeIsOnce = function (list) {
		// ["dbf","prj","shp","shx"];
		var dbf = 0;var prj = 0;var shp = 0;var shx = 0;var sbn = 0;var sbx = 0;var xml = 0;
		$.each(list,function (idx,item) {
			if(item == 'dbf') dbf++;
			if(item == 'prj') prj++;
			if(item == 'shp') shp++;
			if(item == 'shx') shx++;
			if(item == 'sbn') sbn++;
			if(item == 'sbx') sbx++;
			if(item == 'xml') xml++;
		})
		//if(dbf == 1 && prj == 1 && shp == 1 && shx == 1 && sbn < 2 && sbx < 2 && xml < 2) return true;
		if(dbf == 1 && prj < 2 && shp == 1 && shx == 1) return true;
		else return false;
	};
	var judgeName = function (list) {
		var name = list[0];
		var result = list.filter(function (item) {
			return item == name;
		})
		if(result.length == list.length) return true;
		else return false;
	};
	//zyt--校验是否为GDB文件
	var judgeIsOnceGdb = function (list) {
		//判断是否为gdb文件
		var gdb = 0;var timestamps = 0;var atx=0;var gdbindexes=0;var gdbtable=0;var gdbtablx=0;var spx=0;
		$.each(list,function (idx,item) {
			if(item.endsWith("gdb")) gdb++;
			if(item.endsWith("timestamps")) timestamps++;
			if(item.endsWith(".atx")) atx++;
			if(item.endsWith(".gdbindexes")) gdbindexes++;
			if(item.endsWith(".gdbtable")) gdbtable++;
			if(item.endsWith(".gdbtablx")) gdbtablx++;
			if(item.endsWith(".spx")) spx++;
		})
		if(gdb==1 && timestamps==1 && atx>=1 && gdbindexes>=1 && gdbtable>=1 && gdbtablx>=1 && spx>=1){
			return true;
		}else{
			return false;
		}
	};

	var getRiskLevelMapData = function (flag, zoomType, operateType) {
		//clearMarkers();
		loading2.show();
		var bounds = tdMap.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), zoom = tdMap.getZoom();
		var province = $("#provinceSelect2").val(), city = $("#citySelect2").val(), area = $("#areaSelect2").val();
		flag == "3" && (province = $("#provinceSelect3").val(), city = $("#citySelect3").val(), area = $("#areaSelect3").val());
		var formData = {province: province, city: city, area: area, isHaveAuthorityControl: flag == "3" ? "0" : "1",
			bounds: sw.lng + " " + sw.lat + "," + ne.lng + " " + ne.lat, zoom: zoom};
		$.ajax({
			url: getQhRiskLevelMapController() + "/searchQhRiskLevelMaps",
			data: formData,
			//contentType: "application/json",
			type: "POST",
			success: function (result) {
				loading2.close();
				if (typeof(result) == 'string') {
					Util.alert(result);
					return;
				}
				var data = result ? result.data : [], res_zoom = result ? result.zoom : 0;
				clearMarkers(zoomType, operateType, !(data && data.length));
				console.log(data);
				if (data && data.length) {
					affiliatedFileNames = [];fileName2feature = {};
					var total_points = [], affiliatedFileName;
					for (var idx = 0;idx < data.length;idx++) {
						affiliatedFileName = data[idx].affiliatedFileName;
						!isFileNameInObj(affiliatedFileName) && (affiliatedFileNames.push({affiliatedFileName: affiliatedFileName}));
						!fileName2feature[affiliatedFileName] && (fileName2feature[affiliatedFileName] = []);

						var lon = parseFloat(data[idx].a), lat = parseFloat(data[idx].b), lonlat = new T.LngLat(lon, lat);
						lonlat._data = data[idx];
						/*
						//方法【1】的步骤1-1
						var marker = new T.Marker(lonlat, {affiliatedFileName: data[idx].affiliatedFileName, _data: data[idx]});
						//tdMap.addOverLay(marker);
						marker.addEventListener("click", markerClick);
						global_markers.push(marker);
						fileName2feature[affiliatedFileName].push(marker);*/

						//方法【2】的步骤2-1
						if (res_zoom < 15) {
							var options = getOverlayOptions(data[idx].extend3);
							options.affiliatedFileName = data[idx].affiliatedFileName;
							var overlay = new DefinedOverlay(lonlat, data[idx].extend3, options);
							if (global_layer2display[overlay.options.affiliatedFileName] == undefined || global_layer2display[overlay.options.affiliatedFileName]) tdMap.addOverLay(overlay);
							global_overlays.push(overlay);
							fileName2feature[affiliatedFileName].push(overlay);
						}

						total_points.push(lonlat);
					}
					/*
					//方法【1】的步骤1-2
					tdMap.setViewport(total_points);
					global_markerClusterer = new T.MarkerClusterer(tdMap, {markers: global_markers, girdSize: 80, styles: markerClustererStyles});
					*/

					//方法【2】的步骤2-2
					if (res_zoom >= 15) addCloudCollection(total_points, zoomType);
				}
			},
			error: function(xhr, state, errorThrown){
				loading2.close();
				Util.alert("查询数据出现异常!");
			}
		});
	};
	var createAffiliatedFileNameGridGrid = function(flag) {
		var affiliatedFileNameGrid = "affiliatedFileNameGrid" + flag;
		$("#" + affiliatedFileNameGrid).datagrid({
			url: getQhRiskLevelMapController() + "/queryQhRiskLevelMapsByFileName",
			method: "GET",
			fitColumns: true,
			autoRowHeight: false,
			//checkOnSelect: false,
			nowrap: false,
			idField: 'id',
			columns:[[
				{
					field:"ck",
					checkbox: true
				},
				{
					field:'affiliatedFileName',
					title:'文件名称',
					width:'60%',
					align:'center',
					formatter: function (value, rowData, rowIndex) {
						var fileName = rowData.affiliatedFileName, idx = fileName.lastIndexOf("--");
						//(idx != -1) ? (idx = idx + 2) : (idx = 4);
						//(idx != -1) ? (idx = 5) : (idx = 4);
						if (idx != -1) {
							var _district = fileName.substring(5, idx),
								_fileName = fileName.substring(idx + 2, fileName.length - 8),
								_formDate = fileName.substring(fileName.length - 8);
							fileName = _district + "_" + _fileName + "_" + _formDate;
						} else {
							var _c = fileName.substring(4, 5);
							if (_c == "_") idx = 5;
							else idx = 4;
							fileName = (fileName ? (fileName.substring(idx)) : "");
						}

						if (flag == "2") {
							return '<a href="#" onclick="_downloadRiskLevelMapFile(\'' + (rowData.affiliatedFileName) + '\');if(window.event&&window.event.stopPropagation)window.event.stopPropagation();else window.event.cancelBubble=true;"> ' + fileName + ' </a> ';
						} else if (flag == "3") {
							return fileName;
						}
					}
				},
				{
					field:'createTime',
					title:'上传日期',
					width:'40%',
					align:'center',
					sortable: true
				},
			]],
			toolbar: flag == "3" ? [] : (flag == "2" ? [{
				iconCls: 'fa fa-trash-o',
				text:"删除",
				handler: function(){
					deleteFileData(flag);
				}
			}] : []),
			onBeforeLoad: function () {
				$(".datagrid-pager.pagination").hide();
			},
			onLoadSuccess: function () {
				$("#" + affiliatedFileNameGrid).datagrid('selectAll');
				var operatePanel_checkbox = 'operatePanel' + flag + ' input[type=checkbox]';
				$('#' + operatePanel_checkbox).click(function () {
					var rowIndex = $(this).parent().parent().parent().attr("datagrid-row-index");
					var rows = $("#" + affiliatedFileNameGrid).datagrid('getRows'), row = rows[rowIndex];

					/*
					//方法【1】控制图层显示隐藏
					var markers = global_markers, _markers = [];
					for (let i = 0; i < markers.length; i++) {
						if (markers[i].options.affiliatedFileName == row.affiliatedFileName) _markers.push(markers[i]);
					}
					if ($(this).is(":checked")) {
						global_markerClusterer.addMarkers(_markers);
					} else {
						global_markerClusterer.removeMarkers(_markers);
					}*/

					//方法【2】控制图层显示隐藏
					if (tdMap.getZoom() < 15) {
						var overlays = global_overlays, _overlays = [];
						for (let i = 0; i < overlays.length; i++) {
							if (overlays[i].lnglat._data.affiliatedFileName == row.affiliatedFileName) _overlays.push(overlays[i]);
						}
						if ($(this).is(":checked")) {
							for (let i = 0; i < _overlays.length; i++) {
								tdMap.addOverLay(_overlays[i]);
							}
							global_layer2display[row.affiliatedFileName] = true;
						} else {
							for (let i = 0; i < _overlays.length; i++) {
								tdMap.removeOverLay(_overlays[i]);
							}
							global_layer2display[row.affiliatedFileName] = false;
						}
					} else {
						var points = current_points, _points = [], _row;
						$('#' + operatePanel_checkbox).each(function (index, value) {
							if (index == 0) return;
							if ($(value).is(":checked")) {
								_row = rows[index - 1];
								for (let i = 0; i < points.length; i++) {
									if (points[i]._data.affiliatedFileName == _row.affiliatedFileName) _points.push(points[i]);
								}
								global_layer2display[row.affiliatedFileName] = true;
							} else{
								global_layer2display[row.affiliatedFileName] = false;
							}
						});
						collection.setLnglats(_points);
					}


				});
			},
			queryParams: {
				province: flag == "2" ? $("#provinceSelect2").val() : (flag == "3" ? $("#provinceSelect3").val() : ""),
				city: flag == "2" ? $("#citySelect2").val() : (flag == "3" ? $("#citySelect3").val() : ""),
				area: flag == "2" ? $("#areaSelect2").val() : (flag == "3" ? $("#areaSelect3").val() : ""),
				isHaveAuthorityControl: flag == "3" ? "0" : "1",
			},
			pagination: true,
			pageSize: 1000,
			pageList: [ 1000],
		});
	};
	window._downloadRiskLevelMapFile = function (affiliatedFileName) {
		var pca = affiliatedFileName.split("_");
		console.log(affiliatedFileName, pca);
		var province = pca[0], city = pca[1], area = pca[2];
		window.location.href = getQhRiskLevelMapController() + "/download?province=" + province + "&city=" + city + "&area=" + area + "&affiliatedFileName=" + encodeURIComponent(affiliatedFileName);
	};
	var deleteFileData = function () {
		var affiliatedFileNameGrid = "affiliatedFileNameGrid" + global_flag;
		var rows = $("#" + affiliatedFileNameGrid).datagrid("getSelections"), _rows = $('#' + affiliatedFileNameGrid).datagrid('getRows');
		if (rows.length == _rows.length) {
		} else {
			rows = [];
			var operatePanel_checkbox = 'operatePanel' + global_flag + ' input[type=checkbox]';
			$('#' + operatePanel_checkbox).each(function () {
				if ($(this).is(":checked")) {
					var rowIndex = $(this).parent().parent().parent().attr("datagrid-row-index");
					var row = _rows[rowIndex];
					row && rows.push(row);
				}
			});
		}
		console.log(rows)

		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function () {
			var fileNames = "";
			$.each(rows, function (i, row) {
				fileNames += row.affiliatedFileName + ",";
			});
			fileNames = fileNames.substr(0, fileNames.length - 1);
			console.log("fileNames: ", fileNames);
			loading3.show();
			/*
			$.ajax({
				url: getQhRiskLevelMapController() + "/deleteQhRiskLevelMapsByFileNames?fileNames=" + fileNames,
				type: "get",
				success: function (data) {
					loading3.close();
					Util.confirm("删除成功!", function () {
						createAffiliatedFileNameGridGrid();
						getRiskLevelMapData();
					}, function () {
						return;
					});
					var buttons = $(".modal-dialog.modal-sm").find(".modal-footer").children("button");
					if (buttons && buttons.length == 2) {
						buttons.eq(0).html("确定");
						buttons.eq(1).hide();
					}
				},
				error: function(xhr, state, errorThrown){
					loading3.close();
					Util.alert("删除数据出现异常!");
				}
			});
			*/
			$.ajax({
				url: getQhRiskLevelMapController(),
				type: "delete",
				data: {fileNames: fileNames},
				success: function (data) {
					loading3.close();
					Util.confirm("删除成功!", function () {
						createAffiliatedFileNameGridGrid(global_flag);
						getRiskLevelMapData(global_flag, "", "delete");
					}, function () {
						return;
					});
					var buttons = $(".modal-dialog.modal-sm").find(".modal-footer").children("button");
					if (buttons && buttons.length == 2) {
						buttons.eq(0).html("确定");
						buttons.eq(1).hide();
					}
				},
				error: function(xhr, state, errorThrown){
					loading3.close();
					Util.alert("删除数据出现异常!");
				}
			});
		}, function () {
			return;
		});
	};
	var isFileNameInObj = function (fileName) {
		for (let i = 0; i < affiliatedFileNames.length; i++) {
			if (affiliatedFileNames[i].affiliatedFileName == fileName) return true;
		}
		return false;
	};

	var queryQhRiskLevelMapForGrid = function() {
		if (!global_pedId) return;
		$.ajax({
			url: getQhRiskLevelMapController() + "/" + global_pedId,
			contentType: "application/json",
			type: "get",
			success: function (data) {
				console.log(data);
				createQhRiskLevelMapGrid(data ? [data] : [{}]);
			}
		});
	};
	var createQhRiskLevelMapGrid = function(datas) {
		$("#qhRiskLevelMapGrid").datagrid({
			data: datas,
			method: "GET",
			fitColumns: true,
			autoRowHeight: false,
			idField: 'id',
			columns:[[
				//{field:"ck",checkbox:true},
				{
					field:'province',
					title:'省',
					width:'30%',
					align:'center',
				},
				/*{
					field:'city',
					title:'市',
					width:'17%',
					align:'center',

				},
				{
					field:'area',
					title:'区县',
					width:'19%',
					align:'center',
				},*/
				{
					field:'a',
					title:'经度',
					width:'25%',
					align:'center',
				},
				{
					field:'b',
					title:'纬度',
					width:'25%',
					align:'center',

				},
				{
					field:'c',
					title:'危险性等级',
					width:'22.35%',
					align:'center',
				},
			]],
			pagination: true,
			pageSize: 10
		});
	};
	var markerClick = function (e) {
		var data = (e.lnglat && e.lnglat._data) ? e.lnglat._data : e.target.options._data;
		$("#qhRiskLevelMapInfo").show();
		global_pedId = data.uuid;
		queryQhRiskLevelMapForGrid();

		var qhPEDInfo_R = $("#qhRiskLevelMapInfo").css("right");
		console.log(qhPEDInfo_R);
		$("#qhRLMInfoClose").css("right", qhPEDInfo_R);
		$("#qhRLMInfoClose").show();

		$("#operatePanel").css("display", "none");
		$("#operatePanel2").css("display", "none");
		$("#levelMapLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
	};

	var showFieldInfo = function () {
		$("#qhFieldInfo").show();
		var data = [
				{"序号": "1", "数据类型": "浮点型", "是否必填": "是", "注释": "经度", "示例": "119.18"},
				{"序号": "2", "数据类型": "浮点型", "是否必填": "是", "注释": "纬度", "示例": "35.2"},
				{"序号": "3", "数据类型": "整型", "是否必填": "是", "注释": "危险性等级", "示例": "2"},
			];
		$("#qhFieldInfoGrid").datagrid({
			data: data,
			method: "GET",
			//fitColumns: true,
			autoRowHeight: false,
			idField: 'id',
			columns:[[
				//{field:"ck",checkbox:true},
				{
					field:'序号',
					title:'序号',
					width:'10%',
					align:'center',
				},
				{
					field:'数据类型',
					title:'数据类型',
					width:'20%',
					align:'center',

				},
				{
					field:'是否必填',
					title:'是否必填',
					width:'20%',
					align:'center',
				},
				{
					field:'注释',
					title:'注释',
					width:'26%',
					align:'center',
				},
				{
					field:'示例',
					title:'示例',
					width:'27%',
					align:'center',
				},
			]],
			pagination: false,
			pageSize: 13
		});
	};

	var fileName2feature = {}, affiliatedFileNames = [], global_pedId;
	var loading = Loading({text : "正在上传数据..."}), loading2 = Loading({text : "正在查询数据..."}), loading3 = Loading({text : "正在删除数据..."});
	var global_markers = [], global_markerClusterer, global_flag, global_overlays = [], global_layer2display = {};
	var initMap = function() {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
		$("#qhRiskLevelMap").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('qhRiskLevelMap', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

		var control=new T.Control.Zoom();
		tdMap.addControl(control);

		//创建比例尺控件对象
		var scale = new T.Control.Scale();
		tdMap.addControl(scale);

		tdMap.addEventListener("zoomstart", function (e) {
			console.log(e);
			//clearMarkers();
		});
		var isZoomendTo = false;
		tdMap.addEventListener("zoomend", function (e) {
			isZoomendTo = true;
			console.log(e);
			if (global_flag) getRiskLevelMapData(global_flag, "zoomend");
		});

		tdMap.addEventListener("movestart", function (e) {
			//console.log("movestart");
			//clearMarkers();
		});
		tdMap.addEventListener("moveend", function (e) {
			if (isZoomendTo) {
				isZoomendTo = false;
				return;
			}
			console.log(e);
			if (global_flag) getRiskLevelMapData(global_flag, "moveend");
		});
	};
	var clearMarkers = function (zoomType, operateType, isBlank) {
		for (let i = 0; i < global_markers.length; i++) {
			tdMap.removeOverLay(global_markers[i]);
		}
		global_markerClusterer && global_markerClusterer.clearMarkers();
		global_markers = [];

		if (collection && (zoomType == "zoomend" || operateType == "delete" || isBlank)) {
			collection.clear();
			//tdMap.removeOverLay(collection);
			current_points = [];
		}

		for (let i = 0; i < global_overlays.length; i++) {
			tdMap.removeOverLay(global_overlays[i]);
		}
		global_overlays = [];
	};

	var markerClustererStyles = [
		{
			url:'/qhwx/static/app/images/cluster0.png',
			size:[53, 52], //图片大小
			//offset:new T.Point(-15, -13), //显示图片的偏移量
			textColor:'#000000', //显示数字的颜色
			//textSize:8,//显示文字的大小
			range:[0, 50],
		},
		{
			url:'/qhwx/static/app/images/cluster1.png',
			size:[53, 52],
			//offset:new T.Point(-20, -17),
			textColor:'#000000',
			//textSize:10,
			range:[50, 200],
		},
		{
			url:'/qhwx/static/app/images/cluster2.png',
			size:[53, 52],
			//soffset:new T.Point(-10, -22),
			textColor:'#000000',
			//textSize:12,
			range:[200, 500],
		},
		{
			url:'/qhwx/static/app/images/cluster3.png',
			size:[53, 52],
			//soffset:new T.Point(-10, -22),
			textColor:'#000000',
			//textSize:12,
			range:[500, 1000],
		},
		{
			url:'/qhwx/static/app/images/cluster4.png',
			size:[53, 52],
			//soffset:new T.Point(-10, -22),
			textColor:'#000000',
			//textSize:12,
			range:[1000, 100000000000],
		}
	];

	var collection, current_points = [];
	var addCloudCollection = function (lnglats, zoomType) {
		if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
			if (collection) {
				collection.clear();
				if (tdMap.getZoom() >= 15 && zoomType == "moveend") {
					current_points = filterPointsIsInBounds(lnglats, current_points);
				} else {
					current_points = lnglats;
				}
				var _current_points = filterPointsIsDisplay(current_points);
				collection.setLnglats(_current_points);
			} else {
				current_points = lnglats;
				collection = new T.CloudMarkerCollection(current_points, {
					color: 'blue',
					SizeType: TDT_POINT_SIZE_NORMAL
				});
				tdMap.addOverLay(collection);
				collection.addEventListener("click", markerClick);
			}
		} else {
			alert('此功能目前只兼容chrome、safari、IE9及以上浏览器');
		}
	}
	var filterPointsIsInBounds = function (lnglats, points) {
		var isInMap = false, i, len_i, j, len_j, temp_arr = [];
		for (i = 0, len_i = lnglats.length; i < len_i; i++) {
			isInMap = false;
			for (j = 0, len_j = points.length; j < len_j; j++) {
				if (lnglats[i]._data.uuid == points[j]._data.uuid) {
					isInMap = true;
					break;
				}
			}
			if (!isInMap) temp_arr.push(lnglats[i]);
		}
		points = points.concat(temp_arr);

		var bounds = tdMap.getBounds();
		for (let i = 0; i < points.length; i++) {
			if (!(bounds.contains(points[i]))) {
				points.splice(i, 1);
				i--;
			}
		}
		return points;
	}
	var filterPointsIsDisplay = function (points) {
		var _points = [];
		var isDisplay;
		for (let i = 0; i < points.length; i++) {
			isDisplay = global_layer2display[points[i]._data.affiliatedFileName];
			if (!isDisplay && isDisplay != undefined) {
				//points.splice(i, 1);
				//i--;
			} else {
				_points.push(points[i]);
			}
		}
		return _points;
	}

	var DefinedOverlay = T.Overlay.extend({
		initialize: function (lnglat, text, options) {
			this.lnglat = lnglat;
			this.setOptions(options);
			this._text = text;
		},
		onAdd: function (map) {
			this.map = map;
			var div = this._div = document.createElement("div");
			div.style.position = "absolute";
			div.style.width = this.options.size[0] + "px";
			div.style.height = this.options.size[1] + "px";
			div.style.lineHeight = this.options.size[1] + "px";
			div.style.backgroundImage = "url(" + this.options.url + ")";
			div.style.fontSize = "10pt";
			div.style.backgroundSize = "52px 51px";
			div.style.color = this.options.textColor;
			div.style.fontWeight = "700";
			div.style.textAlign = "center";
			div.style.backgroundRepeat = "no-repeat";
			//div.style.backgroundPosition = "-5px";
			div.style.cursor = "pointer";

			var span = document.createElement("span");
			span.appendChild(document.createTextNode(this._text));
			div.appendChild(span);

			map.getPanes().overlayPane.appendChild(this._div);
			this.update(this.lnglat);
		},
		onRemove: function () {
			var parent = this._div.parentNode;
			if (parent) {
				parent.removeChild(this._div);
				this.map = null;
				this._div = null;
			}
		},
		update: function () {
			var pos = this.map.lngLatToLayerPoint(this.lnglat);
			this._div.style.top = ( pos.y - 36) + "px";
			this._div.style.left = (pos.x - 11) + "px";
		}
	});
	var getOverlayOptions = function (num) {
		var option = {};
		if (num >= 0 && num < 80) {
			option = markerClustererStyles[0];
		} else if (num >= 80 && num < 200) {
			option = markerClustererStyles[1];
		} else if (num >= 200 && num < 500) {
			option = markerClustererStyles[2];
		} else if (num >= 500 && num < 1000) {
			option = markerClustererStyles[3];
		} else if (num >= 1000 && num < 100000) {
			option = markerClustererStyles[4];
		} else if (num >= 100000) {
			option = markerClustererStyles[4];
		}
		return option;
	};

	return {
		init:init
	};
});
